package com.uduemc.biso.node.web.component;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.uduemc.biso.core.extities.center.Host;
import com.uduemc.biso.core.extities.pojo.NginxServerConf;
import com.uduemc.biso.core.utils.OSinfoUtil;
import com.uduemc.biso.node.core.property.GlobalProperties;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class NginxOperate {

	@Autowired
	private GlobalProperties globalProperties;

	@Autowired
	private NginxServer nginxServer;

	protected static String exec(Process process) throws IOException {
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
		StringBuffer strbr = new StringBuffer();
		String line;
		while ((line = bufferedReader.readLine()) != null) {
			strbr.append(line).append("\n");
		}

		String result = strbr.toString();

		if (StringUtils.isEmpty(result)) {
			bufferedReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
			strbr = new StringBuffer();
			while ((line = bufferedReader.readLine()) != null) {
				strbr.append(line).append("\n");
			}
			result = strbr.toString();
		}
		return result;
	}

	public String version() throws IOException {
		String base = globalProperties.getNginx().getBase();
		String commond = "";
		if (OSinfoUtil.isWindows()) {
			commond = base + "\\nginx.exe -v";
		} else {
			commond = base + "/sbin/nginx -v";
		}
		log.info(commond);
		Process process = Runtime.getRuntime().exec(commond);
		try {
			int waitFor = process.waitFor();
			log.info("process.waitFor(); " + waitFor);
			if (waitFor != 0) {
				return null;
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
			return null;
		}
		return exec(process);
	}

	public boolean boolTest() throws IOException {
		String base = globalProperties.getNginx().getBase();
		String commond = "";
		if (OSinfoUtil.isWindows()) {
			commond = base + "\\nginx.exe -t -c " + base + "\\conf\\nginx.conf";
		} else {
			commond = base + "/sbin/nginx -t -c " + base + "/conf/nginx.conf";
		}
		log.info(commond);
		Process process = Runtime.getRuntime().exec(commond, null, new File(base));
		try {
			int waitFor = process.waitFor();
			log.info("process.waitFor(); " + waitFor);
			boolean bool = process.waitFor() == 0 ? true : false;
			if (bool == false) {
				log.error(exec(process));
			}
			return bool;
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return false;
	}

	public String test() throws IOException {
		String base = globalProperties.getNginx().getBase();
		String commond = "";
		if (OSinfoUtil.isWindows()) {
			commond = base + "\\nginx.exe -t -c " + base + "\\conf\\nginx.conf";
		} else {
			commond = base + "/sbin/nginx -t -c " + base + "/conf/nginx.conf";
		}
		log.info(commond);
		Process process = Runtime.getRuntime().exec(commond, null, new File(base));
		try {
			int waitFor = process.waitFor();
			log.info("process.waitFor(); " + waitFor);
			if (waitFor != 0) {
				return null;
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
			return null;
		}
		return exec(process);
	}

	public boolean boolReload() throws IOException {
		String base = globalProperties.getNginx().getBase();
		String commond = "";
		if (OSinfoUtil.isWindows()) {
			commond = base + "\\nginx.exe -s reload -c " + base + "\\conf\\nginx.conf";
		} else {
//			commond = base + "/sbin/nginx -s reload -c " + base + "/conf/nginx.conf";
			commond = "/etc/init.d/nginx restart";
		}
		log.info(commond);
		Process process = Runtime.getRuntime().exec(commond, null, new File(base));
		try {
			return process.waitFor() == 0 ? true : false;
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return false;
	}

	public String reload() throws IOException {
		String base = globalProperties.getNginx().getBase();
		String commond = "";
		if (OSinfoUtil.isWindows()) {
			commond = base + "\\nginx.exe -s reload -c " + base + "\\conf\\nginx.conf";
		} else {
//			commond = base + "/sbin/nginx -s reload -c " + base + "/conf/nginx.conf";
			commond = "/etc/init.d/nginx restart";
		}
		log.info(commond);
		Process process = Runtime.getRuntime().exec(commond, null, new File(base));
		try {
			int waitFor = process.waitFor();
			log.info("process.waitFor(); " + waitFor);
			if (waitFor != 0) {
				return null;
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
			return null;
		}
		return exec(process);
	}

	/**
	 * 绑定域名,增加server
	 * 
	 * @return
	 * @throws IOException
	 */
	public synchronized boolean bandleDomain(Host host, NginxServerConf nginxServerConf) throws IOException {
		if (!boolTest()) {
			log.error("nginx -t 测试失败，错误内容：" + test());
			return false;
		}

		if (!nginxServer.make(host, nginxServerConf)) {
			log.error("host生成对应域名的server失败! host: " + host.toString() + " nginxServerConf: " + nginxServerConf.toString());
			return false;
		}

		if (!boolTest()) {
			log.error("host生成对应域名的server后，nginx -t 测试失败! 错误内容: " + test() + " host: " + host.toString() + " nginxServerConf: " + nginxServerConf.toString());
			String makeIncludeFile = nginxServer.makeIncludeFile(host.getId(), nginxServerConf.getServerName());
			File file = new File(makeIncludeFile);
			if (file.isFile()) {
				file.delete();
			}
			return false;
		}

		if (!boolReload()) {
			log.error("host生成对应域名的server后，nginx -s reload 热重启失败! 错误内容: " + reload() + " host: " + host.toString() + " nginxServerConf: "
					+ nginxServerConf.toString());
			String makeIncludeFile = nginxServer.makeIncludeFile(host.getId(), nginxServerConf.getServerName());
			File file = new File(makeIncludeFile);
			if (file.isFile()) {
				file.delete();
			}
			return false;
		}

		return true;
	}
}
